package com.odin.backgrounddownload.downloader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.huawei.hms.network.file.download.api.GetRequest;
import com.odin.backgrounddownload.DownloadParam;
import com.odin.backgrounddownload.Logger;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;

public class SGAndroidGroundDownload extends SGBaseBackGroundDownload
{
    private Queue<DownloadParam> m_WaitQueue = new ArrayDeque<>();
    private Hashtable<Long, DownloadParam> m_DownLoadingSet = new Hashtable<>();

    private HashSet<DownloadParam> m_FinishSet = new HashSet<>();
    private List<Long> m_TmpFinishId = new ArrayList<>();
    private boolean m_IsPause;
    private long m_DownloadedSize;
    private long m_AllDownloadSize;

    private DownloadManager m_DownloadManager;
    private Timer m_Timer;
    DownloadManager.Query m_Query = new DownloadManager.Query();

    public SGAndroidGroundDownload(Activity activity, String cdnUrl, String persistentPath, SGBackGroundDownloadCallback callback)
    {
        super(activity, cdnUrl, persistentPath, callback);

        m_DownloadManager = (DownloadManager)m_UnityMainActivity.getSystemService(Context.DOWNLOAD_SERVICE);
        m_Timer = new Timer();
    }

    @Override
    public void AddDownload(DownloadParam[] downloadParams)
    {
        // 计算需要下载内容总大小
        for (int i = 0; i < downloadParams.length; i++) {
            m_AllDownloadSize += downloadParams[i].getFileSize();
        }
        // 添加到待下载队列
        m_WaitQueue.addAll(Arrays.asList(downloadParams));
    }

    @Override
    public void ForceDownload(DownloadParam downloadParam)
    {
        StartDownload(downloadParam);
    }


    @Override
    public void StartDownload()
    {
        m_IsPause = false;
        FillDownload();

        // 创建一个 TimerTask 对象，用于执行定时任务
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {

                m_TmpFinishId.clear();
                // 检查状态
                for (long id : m_DownLoadingSet.keySet())
                {
                    m_Query.setFilterById(id);
                    Cursor cursor = m_DownloadManager.query(m_Query);
                    if (cursor.getCount() == 0) {
                        // 找不到
                        m_TmpFinishId.add(id);
                    }
                    else
                    {
                        cursor.moveToFirst();
                        @SuppressLint("Range") int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                        @SuppressLint("Range") int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
                        cursor.close();
                        switch (status)
                        {
                            case DownloadManager.STATUS_FAILED:
//                                error = reasonToError(reason);
                                m_TmpFinishId.add(id);
                                break;
                            case DownloadManager.STATUS_SUCCESSFUL:
                                m_TmpFinishId.add(id);
                                break;
                            default:
                                break;
                        }
                    }
                }

                for (long id : m_TmpFinishId)
                {
                    FinishDownload(id);
                }

            }
        };

        // 定义间隔时间和延时时间
        long delay = 1000; // 延时1秒
        long interval = 1000; // 每隔1秒执行一次

        // 定时任务开始执行
        m_Timer.scheduleAtFixedRate(timerTask, delay, interval);
    }


    @Override
    public void PauseDownload() {
        m_IsPause = true;
    }

    @Override
    public long GetDownloadedSize() {
        return m_DownloadedSize;
    }

    @Override
    public long GetAllDownloadSize() {
        return m_AllDownloadSize;
    }

    @Override
    public int QueryDownloadStatus(String urlRelativePath) {
        return 0;
    }

    private void FillDownload()
    {
        while (!m_IsPause && !m_WaitQueue.isEmpty() && m_DownLoadingSet.size() < m_MaxDownloadingCount)
        {
            DownloadParam downloadParam = m_WaitQueue.poll();
            StartDownload(downloadParam);
        }
    }
    private void StartDownload(DownloadParam downloadParam)
    {
        if (m_FinishSet.contains(downloadParam))
        {
            Logger.d("[SGAndroidGroundDownload](StartDownload) m_FinishSet.contains and return:" + downloadParam.getUrlRelativePath() );
            return;
        }

        // 替换成您需要下载的资源地址。
        String normalUrl = AppendPath(m_CdnUrl, downloadParam.getUrlRelativePath());

        if (m_DownLoadingSet.containsKey(normalUrl))
        {
            // 已经在下载了
            return;
        }
        Logger.d("[SGAndroidGroundDownload](StartDownload) " + normalUrl );
        String savePath = AppendPath(m_PersistentPath, downloadParam.getSaveRelativePath());

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(normalUrl));
        request.setDestinationUri(Uri.parse("file://" + savePath));
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
        long id = m_DownloadManager.enqueue(request);

        m_DownLoadingSet.put(id, downloadParam);
    }

    private void FinishDownload(long id)
    {
        DownloadParam param = m_DownLoadingSet.remove(id);
        m_FinishSet.add(param);
        m_DownloadedSize += param.getFileSize();

        Logger.d("[SGAndroidGroundDownload](FinishDownload) " + param.getUrlRelativePath() );
        UpadteNotice();

        if (m_WaitQueue.isEmpty() && m_DownLoadingSet.isEmpty())
        {
            FinishAllDownload();
        }
        else
        {
            FillDownload();
        }
    }

    private void FinishAllDownload()
    {
        m_SGNotificationHelper.CancelNotification();
        // 回调 Unity
    }
}
